package com.nkym.aop;/*
 * @ClassName LoginPointcut
 * @Desc TODO
 * @Author 19637
 * @Date 2023/4/22 21:21
 * @Version 1.0
 */

import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.nkym.annotations.AuthCheck;
import com.nkym.common.ErrorCode;
import com.nkym.constants.UserConstant;
import com.nkym.exception.BusinessException;
import com.nkym.pojo.entity.User;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
public class LoginPointCut {
    @Pointcut("@annotation(com.nkym.annotations.AuthCheck)")
    public void pointCut() {

    }

    @Before(value = "pointCut()")
    public void preHandleAuth(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        //获取注解信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AuthCheck annotation = method.getAnnotation(AuthCheck.class);
        String role = annotation.value();
        HttpServletRequest request = null;
        for (Object arg : args) {
            if (arg instanceof HttpServletRequest) {
                request = (HttpServletRequest) arg;
            }
        }
        if (request == null) {
            throw new BusinessException(ErrorCode.ERROR_CODE);
        }
        HttpSession session = request.getSession();
        //获取登录态
        User user = (User) session.getAttribute(UserConstant.USER_LOGIN_STATUS);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_UNLOGIN);
        }
        if (UserConstant.ROLE_ADMIN.equals(role)) {
            String userRole = user.getUserRole();
            if (!UserConstant.ROLE_ADMIN.equals(userRole)) {
                throw new BusinessException(ErrorCode.FORBIDDEN);
            }
        }
    }

}
